package com.shsmi.jc.seed.controller.api;

import cn.hutool.core.util.StrUtil;
import com.shsmi.jc.seed.common.MyHttpResponse;
import com.shsmi.jc.seed.entity.MapInstance;
import com.shsmi.jc.seed.exception.MyException;
import com.shsmi.jc.seed.service.MapInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/map_instance")
public class MapInstanceController {

    @Autowired
    private MapInstanceService mapInstanceService;

    @GetMapping(path = "/list")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    MyHttpResponse list(@RequestParam(required = false) String map_title,
                        @RequestParam(required = false) String map_type,
                        @RequestParam(required = false, defaultValue = "desc") String sort_type,
                        @RequestParam(required = false, defaultValue = "id") String sort_by,
                        @RequestParam(required = false, defaultValue = "1") Integer page_number,
                        @RequestParam(required = false, defaultValue = "10") Integer page_size) {
        try {
            MapInstance record = new MapInstance();

            if (StrUtil.hasBlank(map_title)) {
                record.setMapTitle(map_title);
            }
            if (StrUtil.hasBlank(map_type)) {
                record.setMapType(map_type);
            }
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("mapTitle", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("mapType", ExampleMatcher.GenericPropertyMatchers.exact());

            Example<MapInstance> example = Example.of(record, matcher);
            return MyHttpResponse.of(true,
                    mapInstanceService.listAll(example, PageRequest.of(page_number - 1, page_size, Sort.Direction.fromString(sort_type), sort_by)),
                    null,
                    null);
        } catch (MyException e) {
            return MyHttpResponse.of(false, null, e.getMessage(), e.getErrorCode());
        } catch (Exception e) {
            return MyHttpResponse.of(false, null, e.getMessage(), null);
        }
    }
}
